<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Payment_model extends CI_Model{
	private static $tableName = 'tbl_buy_goods';
	public function __construct() {
		parent::__construct();
		$this->load->database();
	}
	public function get_payment_by_token_id($token_id) {
		//TODO: get records
		$this->db->where('token_id',$token_id);
		$query = $this->db->get(Payment_model::$tableName);
		if ($query->num_rows() > 0) {
			$result = $query->result();
			//TODO: check reject
			if ($this->check_token_rejected($result[0]->created_date)) {
				return $result;
			}
			else {
				return null;
			}
		}
		else {
			return $query->result();
		}

	}
	public function insert_new_payment_request($user_id, $itemid, $price, $ts, $sig, $token_id) {
		$data = array(
				'user_id' => $user_id,
				'itemid' => $itemid,
				'price' => $price,
				'ts' => $ts,
				'sig' => $sig,
				'token_id' => $token_id
		);
		try {
			$this->db->insert(Payment_model::$tableName, $data);
		}
		catch (Exception $e) {
			//TODO: add logs?
			$this->load->model('log_model');
			$this->log_model->add_log($user_id,'buy_goods','insert_new_payment_request',$e->getMessage(),'insert db');

		}
	}
	public function check_token_rejected($created_date){
		date_default_timezone_set('Asia/Bangkok');
		$c_date = strtotime($created_date);		
		if ((time() - $c_date)>15*60) {
			return false;
		}
		else {
			return true;
		}
	}
}